'use client'

import ResponsiveModal from '@/components/responsive-modal'
import { Button } from '@/components/ui/button'
import { trpc } from '@/lib/trpc'
import { Loader2Icon, PlusIcon } from 'lucide-react'
import React from 'react'
import { toast } from 'sonner'
import StudioUploader from './studio-uploader'
import { useRouter } from 'next/navigation'

export default function StudioUploadModal() {
    const router = useRouter()
    const utils = trpc.useUtils()
    const create = trpc.videos.create.useMutation({
        onSuccess: () => {
            toast.success('Create video success')
            utils.studio.getMany.invalidate()
        },
        onError: (err) => {
            toast.error(err.message)
        }
    })

    const onSuccess = () => {
        if (!create.data?.video.id) return
        create.reset()
        router.push(`/studio/videos/${create.data?.video.id}`)
    }

    return (
        <>
            <ResponsiveModal title='upload a video' open={!!create.data?.url} onOpenChange={() => create.reset()}>
                {create.data?.url ? <StudioUploader endpoint={create.data.url} onSuccess={onSuccess} /> : <Loader2Icon />}
            </ResponsiveModal>
            <Button variant="secondary" className='cursor-pointer' disabled={create.isPending} onClick={() => create.mutate()}>
                {create.isPending ? <Loader2Icon className='animate-spin' /> : <PlusIcon />}
                Create
            </Button>
        </>

    )
}
